package com.itheima.aspectj;


import com.itheima.annotation.AutoFill;
import com.itheima.constant.AutoFillConstant;
import com.itheima.context.BaseContext;
import com.itheima.enumeration.OperationType;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.time.LocalDateTime;

@Slf4j
@Component
@Aspect
public class AutoFillAspect {

    @Before("execution(* com.itheima.mapper.*.*(*))&&@annotation(autoFill)")
    public void before(JoinPoint joinPoint, AutoFill autoFill) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        OperationType value = autoFill.value();
        log.info(value+"=======================");
        if (value==OperationType.INSERT){
            Object pojo = joinPoint.getArgs()[0];

            Method m1 = pojo.getClass().getMethod(AutoFillConstant.SET_CREATE_TIME, LocalDateTime.class);
            Method m2 = pojo.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method m3 = pojo.getClass().getMethod(AutoFillConstant.SET_CREATE_USER, Long.class);
            Method m4 = pojo.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            m1.invoke(pojo,LocalDateTime.now());
            m2.invoke(pojo,LocalDateTime.now());
            m3.invoke(pojo, BaseContext.getCurrentId());
            m4.invoke(pojo, BaseContext.getCurrentId());
        }
        if (value==OperationType.UPDATE){
            Object pojo = joinPoint.getArgs()[0];
            Method m2 = pojo.getClass().getMethod(AutoFillConstant.SET_UPDATE_TIME, LocalDateTime.class);
            Method m4 = pojo.getClass().getMethod(AutoFillConstant.SET_UPDATE_USER, Long.class);
            m2.invoke(pojo,LocalDateTime.now());
            m4.invoke(pojo, BaseContext.getCurrentId());
        }
    }
}
